//
//  HomeDataHelper.m
//  FoodCorner
//
//  Created by Summer on 16/2/27.
//  Copyright © 2016年 Summer. All rights reserved.
//

#import "HomeDataHelper.h"
#import "MainListModel.h"
#import "ImageArrayModel.h"
#import <AVOSCloud.h>
#import <MBProgressHUD/MBProgressHUD.h>
#define kURLSTRING @"http://apis.juhe.cn/cook/index?key=d8ee36cb5b0598e5205ab831d684581a&cid=1&pn=%ld&rn=15"
@interface HomeDataHelper ()
//声明一个转载所有model对象的数组
@property(nonatomic,strong) NSMutableArray *mainDataArray;
//@property(nonatomic,strong) UIAlertView *alert;
@end

@implementation HomeDataHelper
static HomeDataHelper *instance = nil;
+(instancetype)sharedHomeDataHelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HomeDataHelper alloc]init];
    });
    return instance;
}
-(void)findAllDynamicWithLimitNumber:(NSInteger )limitNumber success:(void (^)())success failed:(void (^)(NSString *massage))failed
{
    /*
    //传入所要解析的数据
    NSString *URL = [NSString stringWithFormat:kURLSTRING,page];
    NSLog(@"%@",URL);
    NSString *URL = [kURLSTRING stringByAppendingString:allUrlString];
    //使用AFNetworking解析数据
   
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 100;
    [manager GET:URL parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        //NSLog(@"%@",downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *tempDicts = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableLeaves) error:nil];
            NSDictionary *tempDict = tempDicts[@"result"];
        for (NSDictionary *dic in tempDict[@"data"]) {
            MainListModel *model = [MainListModel new];
            [model setValuesForKeysWithDictionary:dic];
            [self.mainDataArray addObject:model];
    
        }
        
            for (NSDictionary *dict in tempArray) {
                MainListModel *model = [MainListModel new];
                [model setValuesForKeysWithDictionary:dict];
                //[model setValuesForKeysWithDictionary:dict];
                [self.mainDataArray addObject:model];
                NSLog(@"%@",model.imtro);
            }
     
     dispatch_async(dispatch_get_main_queue(), ^{
        success();
    });
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         failed([NSString stringWithFormat:@"%ld",(long)error.code]);
         
     }];
     
    NSURL *urlString = [NSURL URLWithString:URL];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:urlString completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
           NSDictionary *tempDicts = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
            if (data != nil) {
                NSDictionary *tempDict = tempDicts[@"result"];
                for (NSDictionary *dic in tempDict[@"data"]) {
                   MainListModel *model = [MainListModel new];
                   [model setValuesForKeysWithDictionary:dic];
                   [self.mainDataArray addObject:model];
                  
                   
                  
               }
                              dispatch_async(dispatch_get_main_queue(), ^{
                   success();
               });
           }else
           {
               failed(@"数据获取失败");
           }
           
       });
    }];
    
    [dataTask resume];
    */
    AVQuery *query = [MainListModel query];
    query.limit = limitNumber;
    query.cachePolicy = kAVCachePolicyCacheElseNetwork;
    [query orderByAscending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                if (!error) {
                    if (_mainDataArray != nil) {
                        
                        [self.mainDataArray removeAllObjects];
                        
                        for (MainListModel *model in objects) {
                            [self.mainDataArray addObject:model];
                        }
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                       success();
                    });
                }else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                      failed([NSString stringWithFormat:@"数据错误%@",error]);
                    });
                    
                }
            });
    }];
    
    
}
/*
-(void)performDismiss
{
    [_alert dismissWithClickedButtonIndex:0 animated:YES];
}
-(UIAlertView *)alert
{
    if (_alert == nil) {
        _alert = [[UIAlertView alloc]initWithTitle:@"网络错误" message:@"加载中...." delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    }
    return _alert;
}
*/
-(NSMutableArray *)mainDataArray
{
    if (_mainDataArray == nil) {
        _mainDataArray = [NSMutableArray array];
    }
    return _mainDataArray;
}
-(NSInteger)numberOfDatas
{
    return self.mainDataArray.count;
}
- (MainListModel *)modelOfIndex:(NSInteger)index
{
    return self.mainDataArray[index];
}
///将数组遍历到赋值到一个Model，并添加到数组中
- (NSArray *)achieveDataFromArray:(NSArray *)array
{
    NSMutableArray *tempArray = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        
        ImageArrayModel *model = [ImageArrayModel new];
        [model setValuesForKeysWithDictionary:dict];
        [tempArray addObject:model];
    }
    return tempArray;
}
@end
